import {
  createRouter,
  createWebHistory,
  RouteRecordRaw,
  createWebHashHistory,
} from "vue-router";
import { meums } from "./menus";
import store from "@/store";
import { components } from "./menus";
import { eachTreeData } from "@/utils";
import { message } from "ant-design-vue";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "layout",
    meta: { title: "首页" },
    component: () => import("@/layout/index.vue"),
    children: [],
  },
  {
    path: "/login",
    name: "login",
    meta: { type: "system", title: "登录" },
    component: () => import("@/layout/login.vue"),
  },
  {
    path: "/404",
    name: "404",
    meta: { type: "system", title: "404" },
    component: () => import("@/layout/404.vue"),
  },
];

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes,
});

router.beforeEach((to, from, next) => {
  const { title } = to.meta;
  document.title = (title as string) || "";

  const token = store.getters.user.token;
  if (!token && to.path != "/login") {
    next("/login");
  } else loadRoute(to, from, next);
});

export default router;

function loadRoute(to, from, next) {
  const menus = store.getters.user.menus;
  const { type } = to.meta;
  if (!menus && type != "system") {
    // 注册路由
    store.dispatch("user/getMenus").then(async (data) => {
      if (!data) {
        message.error("获取授权菜单失败,请重新登陆");
        next("/login");
        return;
      }
      const { list } = data;
      // menus 同路由字段
      const menus = await clRouteMenus(list);
      store.commit("user/SET", {
        key: "menus",
        value: menus,
      });
      next(menus[0].path);
    });
    return;
  }
  next();
}
// 处理路由菜单
async function clRouteMenus(list) {
  list = list.reverse();
  const routeMenus = [];

  const each = (arr, result = [], parent) => {
    // arr 原数据
    // result 新数据
    // parent 上一级
    arr.map((i) => {
      const { url, display_name, icon } = i;
      const name = String(url).split("/")[1] || null;
      const theme = [
        "/webmasterData",
        "/SEOData",
        "/assetRenewal",
        "/lexiconStatistics",
      ].includes(url)
        ? "dark"
        : null;

      const tempData = {
        name,
        path: url,
        component: components[url] || null,
        meta: {
          title: display_name,
          icon,
          theme,
        },
        children: [],
        redirect: null,
      };
      if (i.children && i.children.length > 0) {
        tempData.children = [];
        tempData.redirect = i.children[0].url;
        each(i.children, tempData.children, i);
      }
      // 判断是否有父级 生成路由
      if (parent) {
        const { url: pUrl } = parent;
        const pName = String(pUrl).split("/")[1] || null;
        router.addRoute(pName, tempData);
      } else router.addRoute("layout", tempData);
      result.push(tempData);
    });
  };

  await each(list, routeMenus, null);

  return routeMenus;
}
